import { MAP_BLOCK_WIDTH, PLAYGROUND_WIDTH, PLAYGROUND_HEIGHT} from "./Setting";

let regions = [];
class MapManager {
	constructor(){
		this.stepC = PLAYGROUND_WIDTH >> MAP_BLOCK_WIDTH; // 32
		this.stepR = PLAYGROUND_HEIGHT >> MAP_BLOCK_WIDTH; // 16

		for(let r = 0; r <= this.stepR; r++){
			regions[r] = [];
			for(let c = 0; c<= this.stepC; c++){
				regions[r][c] = new Map();
			}
		}
	}

	AddToABlock(entity){
		// 计算 食物索引
		let	c = entity.x >> MAP_BLOCK_WIDTH,
			r = entity.y >> MAP_BLOCK_WIDTH;
		try{
			regions[r] && regions[r][c].set(entity.id, entity);
		} catch(e){
			console.error(c, r);
		}
	}

	RemoveFromABlock(entity){
		let	c = entity.x >> MAP_BLOCK_WIDTH,
			r = entity.y >> MAP_BLOCK_WIDTH;
			regions[r] && regions[r][c].delete(entity.id);
	}
	/**
	 * 获取区域
	 * @param {} pos 
	 * @returns 
	 */
	getRegion(pos){
		let	c = pos.x >> MAP_BLOCK_WIDTH,
			r = pos.y >> MAP_BLOCK_WIDTH;
		if(!regions[r]) {
			 debugger
		}
		return regions[r][c];
	}
	
	RefreshBlock(entity, pos){
		let	cbefore = entity.x >> MAP_BLOCK_WIDTH,
			rbefore = entity.y >> MAP_BLOCK_WIDTH,
			cafter = pos.x >> MAP_BLOCK_WIDTH,
			rafter = pos.y >> MAP_BLOCK_WIDTH;
		if(cbefore !== cafter || rbefore !== rafter){
			regions[rbefore] && regions[rbefore][cbefore].delete(entity.id);
			regions[rafter] && regions[rafter][cafter].set(entity.id, entity);
		}
	}

	clear(){
		for(let r = 0; r <= this.stepR; r++){
			regions[r] = [];
			for(let c = 0; c<= this.stepC; c++){
				regions[r][c] = new Map();
			}
		}
	}
}	

export default new MapManager();